package com.misboot.document.utils.minio;

import com.misboot.document.vo.MinioVo;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import io.minio.messages.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @MethodName
 * @Description   minio   http://docs.minio.org.cn/docs/master/java-client-api-reference#getObject
 * @Param null
 * @Return
 * @Author 湖南佐佑时代科技有限公司<service@zuoyo.com>
 * @Date 2020-10-11 17:40
 */

@Component
public class MinioUtil {


    @Autowired
    private MinioClient minioClient;


    /***********************************************存储桶操作************************************************/

    /**
     * 创建一个桶
     */
    public void createBucket(String bucket) throws Exception {
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
    }


    /**
     * 列出所有的桶
     */
    public List<String> listBuckets() throws Exception {
        List<Bucket> list = minioClient.listBuckets();
        List<String> names = new ArrayList<>();
        for(int i = 0; i < list.size(); i++){
            names.add(list.get(i).name());
        }
//        list.forEach(b -> {
//            names.add(b.name());
//        });
        return names;
    }

    /**
     * 检查存储桶是否存在
     */
    public Boolean bucketExists(String bucket) throws IOException, InvalidKeyException, NoSuchAlgorithmException {

        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (found) {
                System.out.println("mybucket exists");
            } else {
                System.out.println("mybucket does not exist");
            }
            return found;
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }


    /**
     * 删除一个桶
     */
    public void deleteBucket(String bucket) throws Exception {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
    }


    /**
     * 列出一个桶中的所有文件和目录
     * bucket 桶名
     * prefix 前缀
     */
    public List<MinioVo> listFiles(String bucket,String prefix) throws Exception {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucket).recursive(false).prefix(prefix).build());

        List<MinioVo> infos = new ArrayList<>();
        results.forEach(r -> {
            MinioVo info = new MinioVo();
            try {
                Item item = r.get();
                info.setSize(item.size());
                info.setFileName(item.objectName());
                info.setDirectory(item.isDir());
                infos.add(info);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return infos;
    }



    /**
     * 列出存储桶中被部分上传的对象。
     */
    public Iterable<Result<Upload>> listIncompleteUploads(String bucketName) {
        try {
            // 检查'mybucket'是否存在。
            boolean found = bucketExists(bucketName);
            if (found) {
                // 列出'mybucket'中所有未完成的multipart上传的的对象。
                Iterable<Result<Upload>> myObjects = listIncompleteUploads(bucketName);
                for (Result<Upload> result : myObjects) {
                    Upload upload = result.get();
                    System.out.println(upload.uploadId() + ", " + upload.objectName());
                }
            } else {
                System.out.println("mybucket does not exist");
            }
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }




    /***********************************************文件操作************************************************/


    /**
     * 以流的形式下载一个文件
     */
    public InputStream download(String bucket, String objectName) throws Exception {
        InputStream stream = minioClient.getObject(
                GetObjectArgs.builder().bucket(bucket).object(objectName).build());
        return stream;
    }



    /**
     * 上传一个文件
     */
    public ObjectWriteResponse uploadFile(InputStream stream, String bucket, String objectName) throws Exception {
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder().bucket(bucket).object(objectName)
                .stream(stream, -1, 10485760).build());
        return objectWriteResponse;
    }




    /**
     * 删除一个对象
     */
    public void deleteObject(String bucket, String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objectName).build());
    }
}
